package com.cn.ycy.controller;

import com.google.common.util.concurrent.RateLimiter;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 限流
 */
@RestController
@RequestMapping("/limiter")
public class LimiterController {

  //每秒只发出5个令牌
  private static RateLimiter rateLimiter = RateLimiter.create(10.0);

  @GetMapping("/get")
  public String getReq() {
    //尝试获取令牌
    if (rateLimiter.tryAcquire()) {
      return "请求成功";
    }
    return "失败";
  }

  public static void main(String[] args) {
    AtomicInteger times = new AtomicInteger();
    try {
      Thread.sleep(2000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    for (int i = 0; i < 100; i++) {
      boolean b = rateLimiter.tryAcquire();
      if(b){
        times.incrementAndGet();
      }
    }
    System.out.println(times.get());
  }

}
